package cn.nfwx.tv.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.NetworkInterface;
import java.net.SocketException;

/**
 * Created by zhouzechao on 2017/12/15.
 */

public class NetworkUtil {
    private static final String TAG = NetworkUtil.class.getSimpleName();
    public static final int NO_NETWORK = 0;
    public static final int WIFI_NETWORK = 1;
    public static final int G_NETWORK = 2;
    public static final int LINE_NETWORK = 3;

    private static final int LOW_SPEED_UPLOAD_BUF_SIZE = 1024;
    private static final int HIGH_SPEED_UPLOAD_BUF_SIZE = 10240;
    private static final int MAX_SPEED_UPLOAD_BUF_SIZE = 102400;
    private static final int LOW_SPEED_DOWNLOAD_BUF_SIZE = 2024;
    private static final int HIGH_SPEED_DOWNLOAD_BUF_SIZE = 30720;
    private static final int MAX_SPEED_DOWNLOAD_BUF_SIZE = 102400;

    private static final int NETWORK_TYPE_IDEN = 11; // Level 8
    private static final int NETWORK_TYPE_EVDO_B = 12; // Level 9
    private static final int NETWORK_TYPE_LTE = 13; // Level 11
    private static final int NETWORK_TYPE_EHRPD = 14; // Level 11
    private static final int NETWORK_TYPE_HSPAP = 15; // Level 13

    //根据Wifi信息获取本地Mac
    public static String getLocalIp(Context context) {
        //在wifi未开启状态下，仍然可以获取MAC地址，但是IP地址必须在已连接状态下否则为0
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = (null == wifiManager ? null : wifiManager.getConnectionInfo());
        if (null != info) {
            return intToIp(info.getIpAddress());
        }
        return null;
    }

    private static String intToIp(int i) {
        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    public static String getMacAddress(Context context) {
        String macAddress = null;
        StringBuffer buf = new StringBuffer();
        NetworkInterface networkInterface = null;
        try {
            networkInterface = NetworkInterface.getByName("eth1");
            if (networkInterface == null) {
                networkInterface = NetworkInterface.getByName("wlan0");
            }
            if (networkInterface == null) {
                return "02:00:00:00:00:02";
            }
            byte[] addr = networkInterface.getHardwareAddress();

            for (byte b : addr) {
                buf.append(String.format("%02X:", b));
            }
            if (buf.length() > 0) {
                buf.deleteCharAt(buf.length() - 1);
            }
            macAddress = buf.toString();
        } catch (SocketException e) {
            e.printStackTrace();
            return "02:00:00:00:00:02";
        }
        return macAddress;
    }

    public static boolean hasNetwork(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null) {
                return networkInfo.isAvailable();
            }
            return false;
        }
        return false;
    }

    /***
     * 1 ：wifi、2:移动网络 、3：有线网络 0、无网络
     */
    public static int getNetworkType(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                //Wifi
                return WIFI_NETWORK;
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                //3G
                return G_NETWORK;
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                //有线
                return LINE_NETWORK;
            }
        }
        return NO_NETWORK;
    }

    /**
     * 判断是不是手机网络
     *
     * @param context
     * @return
     */
    public static boolean isGNetwork(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            return networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
        }
        return false;

    }

    public static boolean isWifiConnection(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if ((networkInfo != null) && (networkInfo.isConnected())) {
            return true;
        }
        return false;
    }

    public static String getWifiSSID(Context context) {
        WifiManager mgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (mgr.isWifiEnabled()) {
            WifiInfo info = mgr.getConnectionInfo();
            return info.getSSID();
        }
        return "";
    }

    public static int getUploadBufSize(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if ((networkInfo != null) && (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
            return MAX_SPEED_UPLOAD_BUF_SIZE;
        }
        if ((networkInfo != null) && (isConnectionFast(networkInfo.getType(), networkInfo.getSubtype()))) {
            return HIGH_SPEED_UPLOAD_BUF_SIZE;
        }
        return LOW_SPEED_UPLOAD_BUF_SIZE;
    }

    public static int getDownloadBufSize(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if ((networkInfo != null) && (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
            return MAX_SPEED_DOWNLOAD_BUF_SIZE;
        }
        if ((networkInfo != null) && (isConnectionFast(networkInfo.getType(), networkInfo.getSubtype()))) {
            return HIGH_SPEED_DOWNLOAD_BUF_SIZE;
        }
        return LOW_SPEED_DOWNLOAD_BUF_SIZE;
    }

    private static boolean isConnectionFast(int type, int subType) {
        if (type == ConnectivityManager.TYPE_WIFI) {
            return true;
        } else if (type == ConnectivityManager.TYPE_MOBILE) {
            switch (subType) {
                case TelephonyManager.NETWORK_TYPE_1xRTT:
                    return false; // ~ 50-100 kbps
                case TelephonyManager.NETWORK_TYPE_CDMA:
                    return false; // ~ 14-64 kbps
                case TelephonyManager.NETWORK_TYPE_EDGE:
                    return false; // ~ 50-100 kbps
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    return true; // ~ 400-1000 kbps
                case TelephonyManager.NETWORK_TYPE_EVDO_A:
                    return true; // ~ 600-1400 kbps
                case TelephonyManager.NETWORK_TYPE_GPRS:
                    return false; // ~ 100 kbps
                case TelephonyManager.NETWORK_TYPE_HSDPA:
                    return true; // ~ 2-14 Mbps
                case TelephonyManager.NETWORK_TYPE_HSPA:
                    return true; // ~ 700-1700 kbps
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                    return true; // ~ 1-23 Mbps
                case TelephonyManager.NETWORK_TYPE_UMTS:
                    return true; // ~ 400-7000 kbps
                // NOT AVAILABLE YET IN API LEVEL 7
                case NETWORK_TYPE_EHRPD:
                    return true; // ~ 1-2 Mbps
                case NETWORK_TYPE_EVDO_B:
                    return true; // ~ 5 Mbps
                case NETWORK_TYPE_HSPAP:
                    return true; // ~ 10-20 Mbps
                case NETWORK_TYPE_IDEN:
                    return false; // ~25 kbps
                case NETWORK_TYPE_LTE:
                    return true; // ~ 10+ Mbps
                // Unknown
                case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                    return false;
                default:
                    return false;
            }
        } else {
            return false;
        }
    }
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

    public static final boolean ping() {

//        String result = null;
//        try {
//            String ip = "www.baidu.com";// 除非百度挂了，否则用这个应该没问题~
//            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);//ping3次
//            // 读取ping的内容，可不加。
//            InputStream input = p.getInputStream();
//            BufferedReader in = new BufferedReader(new InputStreamReader(input));
//            StringBuffer stringBuffer = new StringBuffer();
//            String content = "";
//            while ((content = in.readLine()) != null) {
//                stringBuffer.append(content);
//            }
//            // PING的状态
//            int status = p.waitFor();
//            if (status == 0) {
//                result = "successful~";
//                return true;
//            } else {
//                result = "failed~ cannot reach the IP address";
//            }
//        } catch (IOException e) {
//            result = "failed~ IOException";
//        } catch (InterruptedException e) {
//            result = "failed~ InterruptedException";
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//        }
        return false;

    }


}
